package com.ecar.api.service.common.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ecar.api.service.common.FlightService;
import com.ecar.api.support.dto.FlightExistInfo;
import com.ecar.api.support.util.Props;
import com.ecar.api.support.util.Redis;
import com.ecar.common.dto.DataBean;
import com.ecar.common.util.HttpClientUtil;
import com.ecar.common.util.StringUtil;
import com.ecar.core.common.dao.FlightPersonNumMapper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;

@Service
@Transactional
public class FlightServiceImpl implements FlightService {
	@Autowired
	FlightPersonNumMapper flightPersonNumMapper;

	@Override
	public Integer queryGoPersonNum(Date date1,Date date2) {
		return flightPersonNumMapper.queryGoPersonNum(date1,date2);
	}

	@Override
	public Integer queryArrivePersonNum(Date date1,Date date2 ) {
		return flightPersonNumMapper.queryArrivePersonNum(date1,date2);
	}

	@Override
	public DataBean getFlightInfo(String  flightNo,String date) {
		flightNo = flightNo.replaceAll(" ", "");
		String dateStr;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		long lt = new Long(date);
		dateStr = simpleDateFormat.format(new Date(lt));
		
		Jedis jed = null;
		try {
			jed = Redis.getResource();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 查看该次查询的航班号是否存在缓存中
		//Boolean isExists = jed.exists(flightNo + date);
		
		String string = Redis.c.get(Redis.K.FLIGHT_INFO.to(flightNo + dateStr));
		Boolean isExists = false;
		if (StringUtil.isNotEmpty(string)) {
			isExists = true;
		}
		
		String key = Props.getValue("flight.jh.sk.key");
		String url = Props.getValue("flight.jh.sk.url");
		String urlAll;
		
		int tempDay = 3;// 可选未来的天数 当前版本默认3天 以后版本将会取数据库数据
		FlightExistInfo infoDto = new FlightExistInfo();

		if (!isExists) { // 如果缓存里没有该条数据
			urlAll = new StringBuffer(url).append("?").append("key=").append(key).append("&flightDate=").append(dateStr)
					.append("&flightNo=").append(flightNo).toString();
			System.out.println("开始调航班经停地及起降时间接口,地址为:" + urlAll);

			String jsonResult = HttpClientUtil.httpGet(urlAll);

			if (StringUtil.isEmpty(jsonResult)) {
				return new DataBean(402, new JSONObject(), "航班号错误!");
			}
			System.out.println("查询航班的信息为:" + jsonResult);
			
			// 设置缓存时间为3天
			Redis.c.setex(Redis.K.FLIGHT_INFO.to(flightNo + dateStr),  Redis.DAY*3, jsonResult);
			JSONObject object = JSONObject.fromObject(jsonResult);// 转化为JSON类
			return getArrScheduled(flightNo, tempDay, infoDto, object);

		} else { // 如果缓存里有该条数据
			String jsonResult = Redis.c.get(Redis.K.FLIGHT_INFO.to(flightNo + dateStr));
			
			JSONObject object = JSONObject.fromObject(jsonResult);// 转化为JSON类
			return getArrScheduled(flightNo, tempDay, infoDto, object);
		}
	}
	
	private DataBean getArrScheduled(String flightNo, int tempDay, FlightExistInfo infoDto, JSONObject object) {
		String errorCode = object.getString("error_code");
		switch (errorCode) {
		case "0":
			Object resultStr = object.get("result");
			String VIACities = JSONObject.fromObject(JSONObject.fromObject(resultStr).get("VIACities").toString())
					.getString("VIACity");
			JSONArray VIACity = JSONArray.fromObject(VIACities);

			if (VIACity.size() > 2) {

				for (int i = 0; i < VIACity.size(); i++) {
					String city = JSONObject.fromObject(VIACity.get(i)).getString("city");
					String toTime = JSONObject.fromObject(VIACity.get(i)).getString("toTime");
					String fromTime = JSONObject.fromObject(VIACity.get(i)).getString("fromTime");

					if ("WUH".equals(city) && !"1970-01-01T00:00:00".equals(fromTime)) {
						infoDto.setTempDay(tempDay);
						infoDto.setFlightNo(flightNo);
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
						Date d;
						try {
							d = format.parse(fromTime);
							infoDto.setArrScheduled(d);
							return new DataBean(200, infoDto, "查询成功");
						} catch (ParseException e) {
							e.printStackTrace();
						}
						break;
					}

					if ("WUH".equals(city) && "1970-01-01T00:00:00".equals(fromTime)) {
						infoDto.setTempDay(tempDay);
						infoDto.setFlightNo(flightNo);
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
						Date d;
						try {
							d = format.parse(toTime);
							infoDto.setArrScheduled(d);
							return new DataBean(200, infoDto, "查询成功");
						} catch (ParseException e) {
							e.printStackTrace();
						}
						break;
					}
				}

			} else {

				for (int i = 0; i < VIACity.size(); i++) {
					String city = JSONObject.fromObject(VIACity.get(i)).getString("city");
					String toTime = JSONObject.fromObject(VIACity.get(i)).getString("toTime");

					if ("WUH".equals(city) && !"1970-01-01T00:00:00".equals(toTime)) {
						infoDto.setTempDay(tempDay);
						infoDto.setFlightNo(flightNo);
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
						Date d;
						try {
							d = format.parse(toTime);
							infoDto.setArrScheduled(d);
							return new DataBean(200, infoDto, "查询成功");
						} catch (ParseException e) {
							e.printStackTrace();
						}
						break;
					}
				}

			}

			return new DataBean(400, new JSONObject(), "该航班到达地不在武汉");
		default:
			return new DataBean(401, new JSONObject(), "无该航班信息,请确认航班号和到达时间!");
		}
	}

}
